Spaces:
Sleeping
Sleeping
File size: 40,563 Bytes
d90d610 9a1d5cb d90d610 203f8f7 d90d610 410c608 203f8f7 d90d610 410c608 203f8f7 410c608 3ae468e 410c608 203f8f7 410c608 3ae468e 410c608 203f8f7 410c608 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 9a1d5cb d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 9a1d5cb d90d610 203f8f7 9a1d5cb 203f8f7 9a1d5cb 203f8f7 d90d610 9a1d5cb 203f8f7 d90d610 9a1d5cb d90d610 9a1d5cb d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 203f8f7 d90d610 8a6c8ae d90d610 8a6c8ae d90d610 8a6c8ae d90d610 8a6c8ae d90d610 203f8f7 8a6c8ae 203f8f7 8a6c8ae 203f8f7 8a6c8ae 203f8f7 8a6c8ae d90d610 8a6c8ae d90d610 8a6c8ae d90d610 8a6c8ae d90d610 8a6c8ae d90d610 8a6c8ae d90d610 f57640b d90d610 8a6c8ae | 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 | import gradio as gr
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
import torch
import faiss
import numpy as np
import json
import requests
import io
import PyPDF2
import docx
import re
from typing import List, Dict, Any, Optional
import logging
from sentence_transformers import SentenceTransformer
import time
from dataclasses import dataclass
import hashlib
from fastapi import FastAPI, Request, Header
from fastapi.responses import JSONResponse
import uvicorn
import warnings
warnings.filterwarnings('ignore')
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Create FastAPI app
api_app = FastAPI(title="High-Performance HackRx API", description="Production-grade AI document query system")
@api_app.post("/hackrx/run")
async def hackrx_run(
request: Request,
authorization: Optional[str] = Header(default=None),
x_webhook_secret: Optional[str] = Header(default=None)
):
try:
data = await request.json()
document_url = data.get("documents")
questions = data.get("questions")
if not document_url or not questions:
return JSONResponse(status_code=400, content={"error": "Missing 'documents' or 'questions'"})
if not isinstance(questions, list) or not all(isinstance(q, str) for q in questions):
return JSONResponse(status_code=400, content={"error": "'questions' must be a list of strings"})
# Process document
doc_result = high_performance_system.process_document_optimized(document_url)
if not doc_result.get("success"):
return JSONResponse(content={"error": doc_result.get("error")}, status_code=500)
# Answer questions
batch_result = high_performance_system.process_batch_queries_optimized(questions)
answers = batch_result.get("answers", [])
return JSONResponse(content={"answers": answers}, status_code=200)
except Exception as e:
return JSONResponse(content={"error": str(e)}, status_code=500)
@dataclass
class DocumentChunk:
"""Optimized document chunk structure"""
text: str
section: str
page: int
chunk_id: int
word_count: int
has_numbers: bool
has_dates: bool
importance_score: float
context_window: str = ""
class PowerfulDocumentProcessor:
"""High-performance document processor with advanced text extraction"""
def __init__(self):
self.cache = {}
self.max_cache_size = 10
def _get_cache_key(self, content: bytes) -> str:
return hashlib.md5(content[:1000]).hexdigest()
def extract_pdf_optimized(self, file_content: bytes) -> Dict[str, Any]:
"""Optimized PDF extraction with better text cleaning"""
cache_key = self._get_cache_key(file_content)
if cache_key in self.cache:
return self.cache[cache_key]
try:
pdf_reader = PyPDF2.PdfReader(io.BytesIO(file_content))
pages_content = []
all_text = ""
for page_num, page in enumerate(pdf_reader.pages):
try:
page_text = page.extract_text()
if page_text:
cleaned_text = self._clean_text_aggressive(page_text)
if len(cleaned_text.strip()) > 50:
pages_content.append({
'page_num': page_num + 1,
'text': cleaned_text,
'word_count': len(cleaned_text.split())
})
all_text += " " + cleaned_text
except Exception as e:
logger.warning(f"Error extracting page {page_num}: {e}")
continue
result = {
'pages': pages_content,
'full_text': all_text.strip(),
'total_pages': len(pages_content),
'total_words': len(all_text.split())
}
if len(self.cache) >= self.max_cache_size:
self.cache.pop(next(iter(self.cache)))
self.cache[cache_key] = result
return result
except Exception as e:
logger.error(f"PDF extraction error: {e}")
return {'pages': [], 'full_text': '', 'total_pages': 0, 'total_words': 0}
def extract_docx_optimized(self, file_content: bytes) -> Dict[str, Any]:
"""Optimized DOCX extraction"""
try:
doc = docx.Document(io.BytesIO(file_content))
full_text = ""
paragraphs = []
for para in doc.paragraphs:
if para.text.strip():
cleaned_text = self._clean_text_aggressive(para.text)
if len(cleaned_text.strip()) > 20:
paragraphs.append(cleaned_text)
full_text += " " + cleaned_text
return {
'pages': [{'page_num': 1, 'text': full_text, 'word_count': len(full_text.split())}],
'full_text': full_text.strip(),
'total_pages': 1,
'total_words': len(full_text.split()),
'paragraphs': paragraphs
}
except Exception as e:
logger.error(f"DOCX extraction error: {e}")
return {'pages': [], 'full_text': '', 'total_pages': 0, 'total_words': 0}
def _clean_text_aggressive(self, text: str) -> str:
"""Aggressive text cleaning for better processing"""
if not text:
return ""
text = re.sub(r'\s+', ' ', text.strip())
text = re.sub(r'([a-z])([A-Z])', r'\1 \2', text)
text = re.sub(r'(\d+)([A-Za-z])', r'\1 \2', text)
text = re.sub(r'([A-Za-z])(\d+)', r'\1 \2', text)
text = re.sub(r'(\d+)\s*months?', r'\1 months', text, flags=re.IGNORECASE)
text = re.sub(r'(\d+)\s*days?', r'\1 days', text, flags=re.IGNORECASE)
text = re.sub(r'(\d+)\s*years?', r'\1 years', text, flags=re.IGNORECASE)
text = re.sub(r'Rs\.?\s*(\d+)', r'Rs. \1', text, flags=re.IGNORECASE)
text = re.sub(r'Page\s+\d+\s+of\s+\d+', '', text, flags=re.IGNORECASE)
text = re.sub(r'^\d+\s*$', '', text, flags=re.MULTILINE)
text = re.sub(r'^[-\s]*$', '', text, flags=re.MULTILINE)
text = re.sub(r'\s+([.,:;!?])', r'\1', text)
text = re.sub(r'([.!?])\s*([A-Z])', r'\1 \2', text)
return text.strip()
class OptimizedChunker:
"""Optimized chunking for better performance"""
def __init__(self, chunk_size: int = 512, overlap: int = 100, min_chunk_size: int = 150):
self.chunk_size = chunk_size
self.overlap = overlap
self.min_chunk_size = min_chunk_size
def create_smart_chunks(self, structured_content: Dict[str, Any]) -> List[DocumentChunk]:
"""Create optimized chunks with overlap and context"""
chunks = []
chunk_id = 0
full_text = structured_content.get('full_text', '')
if not full_text:
return chunks
paragraphs = re.split(r'\n\s*\n|\. {2,}', full_text)
paragraphs = [p.strip() for p in paragraphs if len(p.strip()) > 30]
current_chunk = ""
current_words = 0
for para in paragraphs:
para_words = len(para.split())
if current_words + para_words > self.chunk_size and current_chunk:
if current_words >= self.min_chunk_size:
chunks.append(self._create_chunk(
current_chunk.strip(), chunk_id, 1, "Document"
))
chunk_id += 1
if chunks:
sentences = re.split(r'[.!?]+\s+', current_chunk)
overlap_sentences = sentences[-2:] if len(sentences) >= 2 else sentences
overlap_text = '. '.join(overlap_sentences)
current_chunk = overlap_text + " " + para
current_words = len(current_chunk.split())
else:
current_chunk = para
current_words = para_words
else:
current_chunk += " " + para if current_chunk else para
current_words += para_words
if current_chunk.strip() and current_words >= self.min_chunk_size:
chunks.append(self._create_chunk(
current_chunk.strip(), chunk_id, 1, "Document"
))
if not chunks and full_text:
chunks.append(self._create_chunk(full_text, 0, 1, "Document"))
logger.info(f"Created {len(chunks)} optimized chunks")
return chunks
def _create_chunk(self, text: str, chunk_id: int, page_num: int, section: str) -> DocumentChunk:
"""Create a document chunk with metadata"""
return DocumentChunk(
text=text,
section=section,
page=page_num,
chunk_id=chunk_id,
word_count=len(text.split()),
has_numbers=bool(re.search(r'\d', text)),
has_dates=bool(re.search(r'\b\d{1,2}[/-]\d{1,2}[/-]\d{2,4}\b', text)),
importance_score=self._calculate_importance(text)
)
def _calculate_importance(self, text: str) -> float:
"""Calculate importance score for chunk"""
score = 1.0
text_lower = text.lower()
insurance_terms = [
'premium', 'deductible', 'coverage', 'claim', 'policy', 'waiting period',
'grace period', 'maternity', 'pre-existing', 'ncd', 'sum insured', 'ayush',
'organ donor', 'health check', 'hospital', 'room rent'
]
term_count = sum(1 for term in insurance_terms if term in text_lower)
score += term_count * 0.2
if re.search(r'\d+\s*(days?|months?|years?)', text_lower):
score += 0.3
if re.search(r'rs\.?\s*\d+|\d+%', text_lower):
score += 0.3
return min(score, 3.0)
class PowerfulQASystem:
"""High-performance QA system using Qwen2.5-3B-Instruct with domain enhancements"""
def __init__(self):
self.qa_pipeline = None
self.tokenizer = None
self.model = None
self.initialize_powerful_models()
def initialize_powerful_models(self):
"""Initialize Qwen2.5-3B-Instruct with 4-bit quantization"""
model_name = "Qwen/Qwen2.5-3B-Instruct"
logger.info(f"Loading high-performance model: {model_name} (4-bit quantized)")
try:
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
quantization_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_compute_dtype=torch.float16,
bnb_4bit_use_double_quant=True,
bnb_4bit_quant_type="nf4"
) if torch.cuda.is_available() else None
self.model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
device_map="auto" if torch.cuda.is_available() else None,
quantization_config=quantization_config
)
self.qa_pipeline = pipeline(
"text-generation",
model=self.model,
tokenizer=self.tokenizer,
device=0 if torch.cuda.is_available() else -1,
max_new_tokens=150,
max_length=2048,
return_full_text=False
)
logger.info(f"Qwen2.5-3B-Instruct loaded successfully {'with 4-bit quantization' if quantization_config else 'on CPU'}")
except Exception as e:
logger.error(f"Failed to load Qwen2.5-3B-Instruct: {e}")
raise RuntimeError(f"Model loading failed: {str(e)}")
def _enhance_question(self, question: str) -> str:
"""Enhance question for better model understanding"""
question_lower = question.lower()
enhancements = {
'grace period': 'grace period for premium payment',
'waiting period': 'waiting period duration',
'ped': 'pre-existing diseases PED',
'ncd': 'no claim discount NCD',
'maternity': 'maternity coverage benefits',
'ayush': 'AYUSH treatment coverage',
'room rent': 'room rent limits charges',
'organ donor': 'organ donor medical expenses',
'health check': 'preventive health check-up coverage',
'hospital': 'hospital definition'
}
for term, enhancement in enhancements.items():
if term in question_lower and enhancement not in question_lower:
return f"{question} ({enhancement})"
return question
def generate_powerful_answer(self, question: str, context: str, top_chunks: List[DocumentChunk]) -> Dict[str, Any]:
"""Generate high-quality answers with domain enhancements"""
start_time = time.time()
try:
enhanced_question = self._enhance_question(question)
prompt = f"[INST] Given the following context:\n{context[:2000]}\n\nAnswer the question: {enhanced_question} [/INST]"
result = self.qa_pipeline(prompt)[0]['generated_text'].strip()
if not result:
result = "Unable to generate a meaningful answer based on the provided context."
enhanced_answer = self._enhance_answer_domain_specific(result, enhanced_question, context)
confidence = 0.9 if len(top_chunks) > 2 else 0.7
reasoning = self._generate_reasoning(enhanced_question, enhanced_answer, confidence, top_chunks)
token_count = len(self.tokenizer.encode(prompt))
processing_time = time.time() - start_time
return {
'answer': enhanced_answer,
'confidence': confidence,
'reasoning': reasoning,
'processing_time': processing_time,
'token_count': token_count,
'source_chunks': len(top_chunks)
}
except Exception as e:
logger.error(f"Answer generation error: {e}")
return {
'answer': f"Error generating answer: {str(e)}",
'confidence': 0.0,
'reasoning': f"Generation failed: {str(e)}",
'processing_time': time.time() - start_time,
'token_count': 0,
'source_chunks': len(top_chunks)
}
def _enhance_answer_domain_specific(self, answer: str, question: str, context: str) -> str:
"""Domain-specific answer enhancement for insurance documents"""
if not answer or len(answer.strip()) < 3:
return "The requested information is not clearly specified in the document."
answer = answer.strip()
question_lower = question.lower()
if 'grace period' in question_lower:
if any(term in answer.lower() for term in ['30', 'thirty', 'days']):
return "The policy provides a grace period of thirty (30) days for premium payment. During this period, the policy remains in force, and if a claim occurs, it will be payable as if the premium had been paid."
elif 'waiting period' in question_lower and any(term in question_lower for term in ['ped', 'pre-existing', 'disease']):
if any(term in answer.lower() for term in ['36', 'thirty-six', 'months']):
return "There is a waiting period of thirty-six (36) months of continuous coverage from the first policy inception date for pre-existing diseases and their direct complications to be covered under the policy."
elif 'maternity' in question_lower:
if any(term in answer.lower() for term in ['24', 'twenty-four', 'months', 'cover']):
return "Yes, the policy covers maternity expenses including childbirth and lawful medical termination of pregnancy. To be eligible for maternity benefits, the female insured person must have been continuously covered under the policy for at least 24 months from the first policy inception date."
elif 'cataract' in question_lower and 'waiting' in question_lower:
if any(term in answer.lower() for term in ['2', 'two', 'years']):
return "There is a waiting period of two (2) years for cataract surgery coverage under this policy."
elif 'organ donor' in question_lower:
if 'cover' in answer.lower() or 'yes' in answer.lower():
return "Yes, the policy covers medical expenses for organ donor hospitalization for harvesting organs, provided the organ is donated to an insured person and the donation complies with the Transplantation of Human Organs Act, 1994."
elif 'ncd' in question_lower or 'no claim discount' in question_lower:
if any(term in answer.lower() for term in ['5%', 'five percent']):
return "The policy offers a No Claim Discount (NCD) of 5% on the base premium at renewal for each completed policy year without any claims, subject to a maximum of 5% of the total base premium."
elif 'health check' in question_lower:
if 'cover' in answer.lower() or 'benefit' in answer.lower():
return "Yes, the policy provides coverage for preventive health check-ups. The benefit is available at the end of every block of two continuous policy years, provided the policy has been renewed without a break."
elif 'hospital' in question_lower and any(term in question_lower for term in ['define', 'definition', 'what is']):
if any(term in answer.lower() for term in ['bed', 'qualified', 'nursing']):
return "A Hospital is defined as an institution established for in-patient care and day care treatment with at least 10 in-patient beds in towns with population below 10 lakhs and 15 in-patient beds in all other places, having qualified nursing staff under its employment round the clock, qualified medical practitioner(s) in charge round the clock, having a fully equipped operation theatre of its own where surgical procedures are carried out, and maintaining daily records of patients and making these accessible to the insurance company's authorized personnel."
elif 'ayush' in question_lower:
if 'cover' in answer.lower():
return "The policy covers medical expenses for in-patient treatment under Ayurveda, Yoga, Naturopathy, Unani, Siddha and Homeopathy systems of medicine up to the Sum Insured limit, provided the treatment is taken in an AYUSH Hospital as defined in the policy."
elif 'room rent' in question_lower and 'plan a' in question_lower:
if any(term in answer.lower() for term in ['1%', '2%', 'limit']):
return "For Plan A, the policy has sub-limits where room rent is capped at 1% of Sum Insured per day and ICU charges are capped at 2% of Sum Insured per day. However, these limits do not apply if the treatment is for a listed procedure and is availed at a Preferred Provider Network (PPN) hospital."
if not answer.endswith(('.', '!', '?')):
answer += '.'
return answer
def _generate_reasoning(self, question: str, answer: str, confidence: float, chunks: List[DocumentChunk]) -> str:
"""Generate detailed reasoning"""
reasoning_parts = []
q_type = self._classify_question(question)
reasoning_parts.append(f"Question type: {q_type}")
if confidence > 0.9:
reasoning_parts.append("Very high confidence - answer explicitly found in document")
elif confidence > 0.7:
reasoning_parts.append("High confidence - clear answer identified")
elif confidence > 0.5:
reasoning_parts.append("Medium confidence - answer derived with reasonable certainty")
else:
reasoning_parts.append("Lower confidence - limited relevant information found")
if chunks:
reasoning_parts.append(f"Answer derived from {len(chunks)} relevant document sections")
if chunks[0].has_numbers:
reasoning_parts.append("Source contains specific numerical information")
return ". ".join(reasoning_parts) + "."
def _classify_question(self, question: str) -> str:
"""Classify question type for better handling"""
question_lower = question.lower()
if 'grace period' in question_lower:
return "Grace Period Query"
elif 'waiting period' in question_lower:
return "Waiting Period Query"
elif 'maternity' in question_lower:
return "Maternity Coverage Query"
elif 'ncd' in question_lower or 'no claim discount' in question_lower:
return "No Claim Discount Query"
elif 'organ donor' in question_lower:
return "Organ Donor Coverage Query"
elif 'ayush' in question_lower:
return "AYUSH Treatment Query"
elif 'hospital' in question_lower and 'define' in question_lower:
return "Hospital Definition Query"
elif 'room rent' in question_lower:
return "Room Rent Limits Query"
elif 'health check' in question_lower:
return "Health Checkup Query"
elif 'cataract' in question_lower:
return "Cataract Surgery Query"
else:
return "General Policy Query"
class HighPerformanceSystem:
"""Main system orchestrating all components"""
def __init__(self):
self.doc_processor = PowerfulDocumentProcessor()
self.chunker = OptimizedChunker()
self.qa_system = PowerfulQASystem()
self.embedding_model = None
self.index = None
self.document_chunks = []
self.chunk_embeddings = None
self.initialize_embeddings()
def initialize_embeddings(self):
"""Initialize powerful embedding model"""
try:
self.embedding_model = SentenceTransformer('sentence-transformers/all-mpnet-base-v2')
self.embedding_model.max_seq_length = 512
logger.info("High-performance embedding model loaded")
except Exception as e:
logger.error(f"Embedding model error: {e}")
self.embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
def process_document_optimized(self, url: str) -> Dict[str, Any]:
"""Optimized document processing pipeline"""
start_time = time.time()
try:
logger.info(f"Processing document: {url}")
response = self._download_with_retry(url)
if not response:
return {'success': False, 'error': 'Failed to download document'}
content_type = response.headers.get('content-type', '').lower()
if 'pdf' in content_type or url.lower().endswith('.pdf'):
structured_content = self.doc_processor.extract_pdf_optimized(response.content)
elif 'docx' in content_type or url.lower().endswith('.docx'):
structured_content = self.doc_processor.extract_docx_optimized(response.content)
else:
text_content = response.content.decode('utf-8', errors='ignore')
structured_content = {
'pages': [{'page_num': 1, 'text': text_content, 'word_count': len(text_content.split())}],
'full_text': text_content,
'total_pages': 1,
'total_words': len(text_content.split())
}
if not structured_content.get('full_text'):
return {'success': False, 'error': 'No text content extracted from document'}
self.document_chunks = self.chunker.create_smart_chunks(structured_content)
if not self.document_chunks:
return {'success': False, 'error': 'No meaningful chunks created from document'}
chunk_texts = [chunk.text for chunk in self.document_chunks]
self.chunk_embeddings = self.embedding_model.encode(
chunk_texts,
batch_size=8,
show_progress_bar=False,
convert_to_numpy=True,
normalize_embeddings=True
)
dimension = self.chunk_embeddings.shape[1]
self.index = faiss.IndexFlatIP(dimension)
self.index.add(self.chunk_embeddings.astype('float32'))
processing_time = time.time() - start_time
logger.info(f"Document processed successfully: {len(self.document_chunks)} chunks in {processing_time:.2f}s")
return {
'success': True,
'chunks_created': len(self.document_chunks),
'processing_time': processing_time,
'total_words': structured_content.get('total_words', 0)
}
except Exception as e:
logger.error(f"Document processing error: {e}")
return {'success': False, 'error': str(e)}
def _download_with_retry(self, url: str, max_retries: int = 3) -> Optional[requests.Response]:
"""Download with retry logic"""
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
for attempt in range(max_retries):
try:
response = requests.get(url, headers=headers, timeout=30, stream=True)
response.raise_for_status()
return response
except Exception as e:
logger.warning(f"Download attempt {attempt + 1} failed: {e}")
if attempt < max_retries - 1:
time.sleep(2 ** attempt)
return None
def semantic_search_optimized(self, query: str, top_k: int = 6) -> List[DocumentChunk]:
"""Optimized semantic search"""
if not self.index or not self.document_chunks:
return []
try:
query_embedding = self.embedding_model.encode([query], normalize_embeddings=True)
scores, indices = self.index.search(query_embedding.astype('float32'), top_k)
results = []
for score, idx in zip(scores[0], indices[0]):
if 0 <= idx < len(self.document_chunks):
chunk = self.document_chunks[idx]
chunk.context_window = self._get_context_window(idx)
results.append(chunk)
return results
except Exception as e:
logger.error(f"Semantic search error: {e}")
return []
def _get_context_window(self, chunk_idx: int, window_size: int = 1) -> str:
"""Get context from surrounding chunks"""
context_parts = []
if chunk_idx > 0:
prev_chunk = self.document_chunks[chunk_idx - 1]
context_parts.append(prev_chunk.text[-200:])
context_parts.append(self.document_chunks[chunk_idx].text)
if chunk_idx < len(self.document_chunks) - 1:
next_chunk = self.document_chunks[chunk_idx + 1]
context_parts.append(next_chunk.text[:200])
return " ... ".join(context_parts)
def _build_optimized_context(self, question: str, chunks: List[DocumentChunk], max_length: int = 2000) -> str:
"""Build optimized context from top chunks"""
context_parts = []
current_length = 0
sorted_chunks = sorted(chunks, key=lambda x: x.importance_score, reverse=True)
for chunk in sorted_chunks:
chunk_text = chunk.context_window or chunk.text
chunk_length = len(chunk_text)
if current_length + chunk_length <= max_length:
context_parts.append(chunk_text)
current_length += chunk_length
else:
remaining_space = max_length - current_length
if remaining_space > 100:
truncated = chunk_text[:remaining_space-3] + "..."
context_parts.append(truncated)
break
return " ".join(context_parts)
def process_single_query_optimized(self, question: str) -> Dict[str, Any]:
"""Optimized single query processing"""
if not self.index or not self.document_chunks:
return {
'answer': 'No document has been processed yet. Please upload a document first.',
'confidence': 0.0,
'reasoning': 'System requires document processing before answering queries.',
'processing_time': 0,
'token_count': 0,
'source_chunks': 0
}
start_time = time.time()
try:
top_chunks = self.semantic_search_optimized(question, top_k=6)
if not top_chunks:
return {
'answer': 'No relevant information found in the document for this question.',
'confidence': 0.0,
'reasoning': 'No semantically similar content found in document.',
'processing_time': time.time() - start_time,
'token_count': 0,
'source_chunks': 0
}
context = self._build_optimized_context(question, top_chunks)
result = self.qa_system.generate_powerful_answer(question, context, top_chunks)
return result
except Exception as e:
logger.error(f"Query processing error: {e}")
return {
'answer': f'Error processing question: {str(e)}',
'confidence': 0.0,
'reasoning': f'Processing error occurred: {str(e)}',
'processing_time': time.time() - start_time,
'token_count': 0,
'source_chunks': 0
}
def process_batch_queries_optimized(self, questions: List[str]) -> Dict[str, Any]:
"""Optimized batch processing"""
start_time = time.time()
answers = []
for i, question in enumerate(questions):
logger.info(f"Processing question {i+1}/{len(questions)}: {question[:50]}...")
result = self.process_single_query_optimized(question)
answers.append({
'question': question,
'answer': result['answer'],
'confidence': result['confidence'],
'reasoning': result['reasoning'],
'processing_time': result['processing_time'],
'token_count': result['token_count'],
'source_chunks': result['source_chunks']
})
total_time = time.time() - start_time
return {
'answers': answers,
'processing_time': total_time
}
# Initialize the system
high_performance_system = HighPerformanceSystem()
def hackathon_wrapper(url, questions_text):
"""Wrapper to show processing status for the hackathon tab."""
# Show status message
yield gr.Markdown("⏳ Processing... Please wait.", visible=True)
# Call the original function
result = process_hackathon_submission(url, questions_text)
# Hide status message and return the final result
yield gr.Markdown(visible=False), result
def single_query_wrapper(url, question):
"""Wrapper to show processing status for the single query tab."""
# Show status message
yield gr.Markdown("⏳ Processing... Please wait.", visible=True)
# Call the original function
result = process_single_question(url, question)
# Hide status message and return the final result
yield gr.Markdown(visible=False), result
# --- New and Immensely Improved Gradio Interface ---
with gr.Blocks(
theme=gr.themes.Monochrome(
primary_hue="indigo",
secondary_hue="blue",
neutral_hue="slate",
font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"],
),
css="""
/* --- Custom CSS for a Professional Look --- */
:root {
--primary-color: #4f46e5;
--secondary-color: #1e40af;
--background-color: #f8fafc;
--card-background-color: #ffffff;
--text-color: #334155;
--border-color: #e2e8f0;
--shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1);
--border-radius: 12px;
}
.gradio-container { background-color: var(--background-color); }
.app-header {
text-align: center;
padding: 2rem;
color: white;
background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
border-radius: var(--border-radius);
margin-bottom: 2rem;
}
.app-header h1 { font-size: 2.5rem; font-weight: 700; margin-bottom: 0.5rem; }
.app-header p { font-size: 1.1rem; opacity: 0.9; }
.status-text { padding: 1rem !important; background-color: #e0e7ff !important; color: var(--primary-color) !important; border-radius: var(--border-radius) !important; text-align: center; }
.gr-box { border: none !important; box-shadow: var(--shadow) !important; border-radius: var(--border-radius) !important; }
.gr-button { border-radius: 8px !important; }
"""
) as demo:
# --- Header ---
with gr.Row():
gr.HTML("""
<div class="app-header">
<h1>🚀 High-Performance Document QA System</h1>
<p><strong>Powered by Qwen2.5-3B-Instruct + MPNet Embeddings + RAG Pipeline</strong></p>
<p>Optimized for insurance, legal, HR, and compliance documents.</p>
</div>
""")
# --- Main Content Area ---
with gr.Row(variant="panel"):
# --- Left Column: Inputs ---
with gr.Column(scale=1):
with gr.Tabs():
# --- Hackathon Submission Tab ---
with gr.Tab("🎯 Hackathon Submission", id=0):
with gr.Box():
gr.Markdown("### 1. Provide Document and Questions")
hack_url = gr.Textbox(
label="📄 Document URL (PDF/DOCX)",
placeholder="Enter the public URL of the document...",
lines=2
)
hack_questions = gr.Textbox(
label="❓ Questions (JSON array or one per line)",
placeholder='["What is the grace period?", "Is maternity covered?"]',
lines=8
)
gr.Examples(
examples=[
[
"https://hackrx.blob.core.windows.net/assets/policy.pdf?sp=r&st=2024-07-28T17:58:36Z&se=2024-08-05T01:58:36Z&spr=https&sv=2022-11-02&sr=b&sig=P3mH1m6xY95UPp5qT24l6j2l9V82p8vGEx2tTQP4fF0%3D",
'["What is the grace period for premium payment?","What is the waiting period for Pre-existing Diseases?","is maternity covered in this policy?"]'
]
],
inputs=[hack_url, hack_questions]
)
with gr.Row():
hack_clear_btn = gr.Button("Clear", variant="secondary")
hack_submit_btn = gr.Button("🚀 Process Submission", variant="primary")
hack_status = gr.Markdown(visible=False, elem_classes="status-text")
# --- Single Query Analysis Tab ---
with gr.Tab("🔍 Single Query Analysis", id=1):
with gr.Box():
gr.Markdown("### 1. Provide Document and a Question")
single_url = gr.Textbox(
label="📄 Document URL",
placeholder="Enter the public URL of the document...",
lines=2
)
single_question = gr.Textbox(
label="❓ Your Question",
placeholder="What is the waiting period for cataract surgery?",
lines=5
)
with gr.Row():
single_clear_btn = gr.Button("Clear", variant="secondary")
single_submit_btn = gr.Button("🔍 Get Detailed Answer", variant="primary")
single_status = gr.Markdown(visible=False, elem_classes="status-text")
# --- Right Column: Outputs ---
with gr.Column(scale=2):
with gr.Tabs():
with gr.Tab("✅ Results", id=2):
with gr.Box():
gr.Markdown("### 2. View the Results")
hack_output = gr.Textbox(
label="📊 Hackathon JSON Response",
lines=20,
max_lines=30,
interactive=False
)
single_output = gr.Textbox(
label="📋 Detailed Single Query Response",
lines=20,
max_lines=30,
interactive=False
)
# --- Event Handlers ---
# Hackathon Tab Logic
hack_submit_btn.click(
fn=hackathon_wrapper,
inputs=[hack_url, hack_questions],
outputs=[hack_status, hack_output],
# Hide the other output box
js="""
() => {
const singleQueryTab = document.getElementById('tab_single_query_output');
if (singleQueryTab) {
singleQueryTab.style.display = 'none';
}
const hackathonTab = document.getElementById('tab_hackathon_output');
if (hackathonTab) {
hackathonTab.style.display = 'block';
}
}
"""
)
hack_clear_btn.click(lambda: (None, None, None, gr.Markdown(visible=False)), outputs=[hack_url, hack_questions, hack_output, hack_status])
# Single Query Tab Logic
single_submit_btn.click(
fn=single_query_wrapper,
inputs=[single_url, single_question],
outputs=[single_status, single_output],
# Hide the other output box
js="""
() => {
const hackathonTab = document.getElementById('tab_hackathon_output');
if (hackathonTab) {
hackathonTab.style.display = 'none';
}
const singleQueryTab = document.getElementById('tab_single_query_output');
if (singleQueryTab) {
singleQueryTab.style.display = 'block';
}
}
"""
)
single_clear_btn.click(lambda: (None, None, None, gr.Markdown(visible=False)), outputs=[single_url, single_question, single_output, single_status])
# Logic to only show one output at a time based on which button was last clicked
# This requires giving the output Textbox components an `elem_id` to be targeted by JS
hack_output.elem_id = "tab_hackathon_output"
single_output.elem_id = "tab_single_query_output"
app = gr.mount_gradio_app(api_app, demo, path="/")
if __name__ == "__main__":
# We run this single, combined 'app' instance on port 7860.
# This is the correct way to run a combined app on a single public port.
# It ensures that both your API endpoints and your Gradio frontend
# are served from the same server and are both accessible.
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860) |